package com.heima.search.service.impl;

import com.heima.common.search.ElasticSearchTemplate;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.SearchService;
import com.heima.search.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.*;

/**
 * @author 霍森彪
 * @date 2022/7/25 11:30
 */

@Service
@Slf4j
public class SearchServiceImpl implements SearchService {

    @Autowired
    private ElasticSearchTemplate elasticSearchTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        //判空
        if (dto == null || StringUtils.isBlank(dto.getSearchWords())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //提取入参
        int pageNum = dto.getPageNum();
        int pageSize = dto.getPageSize();
        String searchWords = dto.getSearchWords();
        Date minBehotTime = dto.getMinBehotTime();

        //关键字查询
        QueryStringQueryBuilder stringQueryBuilder = elasticSearchTemplate.getStringQueryBuilder(searchWords, Operator.OR, "title", "content");

        //时间范围查询
        Map<String, Object> rangeCondition = new HashMap<>(1);
        rangeCondition.put("lt", minBehotTime.getTime());
        RangeQueryBuilder rangeQueryBuilder = elasticSearchTemplate.getRangeBuilder("publishTime", rangeCondition);

        //布尔查询
        Map<String, AbstractQueryBuilder> boolCondition = new HashMap<>();
        boolCondition.put("must", stringQueryBuilder);
        boolCondition.put("filter", rangeQueryBuilder);
        BoolQueryBuilder boolQueryBuilder = elasticSearchTemplate.getBoolQueryBuilder(boolCondition);

        //高亮
        HighlightBuilder highlightBuilder = elasticSearchTemplate.getHighlightBuilder("title", "<font style='color: red; font-size: inherit;'>", "</font>");

        //执行查询
        SearchResponse response = elasticSearchTemplate.search("app_info_article", boolQueryBuilder, highlightBuilder, pageNum, pageSize, "publishTime", SortOrder.DESC);

        //保存用户搜索记录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        Integer userId = user.getId();
        if (userId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        insert(searchWords, userId);
        //提取结果
        SearchHit[] hits = response.getHits().getHits();

        List<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit hit : hits) {

            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();

            //处理高亮显示
            if (!CollectionUtils.isEmpty(highlightFields)) {
                Text[] titles = highlightFields.get("title").getFragments();
                String join = StringUtils.join(titles, ",");
                sourceAsMap.put("h_title", join);
            } else {
                sourceAsMap.put("h_title", sourceAsMap.get("title"));
            }

            list.add(sourceAsMap);
        }
        return ResponseResult.okResult(list);
    }


    /**
     * 保存用户搜索历史记录
     * @param keyword
     * @param userId
     */
    @Override
    @Async
    public void insert(String keyword, Integer userId) {
        //1.查询当前用户的搜索关键词
        Query query = Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyword));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);

        //2.存在 更新创建时间
        if(apUserSearch != null){
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }

        //3.不存在，判断当前历史记录总数量是否超过10
        apUserSearch = new ApUserSearch();
        apUserSearch.setUserId(userId);
        apUserSearch.setKeyword(keyword);
        apUserSearch.setCreatedTime(new Date());

        Query query1 = Query.query(Criteria.where("userId").is(userId));
        query1.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApUserSearch> apUserSearchList = mongoTemplate.find(query1, ApUserSearch.class);

        if(apUserSearchList == null || apUserSearchList.size() < 10){
            mongoTemplate.save(apUserSearch);
        }else {
            ApUserSearch lastUserSearch = apUserSearchList.get(apUserSearchList.size() - 1);
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(lastUserSearch.getId())),apUserSearch);
        }
    }
}
